<template>
  <div class="messageWarp">
    <div style="flex-grow: 1">
      <a-table
        :columns="columns"
        :data-source="lianluData.zongjuList"
        bordered
        :autoDataLoad="false"
        size="small"
        :pagination="false"
      >
        <template #bodyCell="{ column, record  }">
          <template v-if="column.dataIndex === 'lianlu_code'">
            <a-select
              ref="select"
              v-model:value="record.lianlu_code"
              style="width: 100%"
              :showSearch="true"
              allowClear
            >
              <a-select-option value="请选择节点名称" disabled>请选择节点名称</a-select-option>
              <a-select-option
                v-for="item in zongjuLianluData"
                :key="item.lianlu_code"
                :value="item.lianlu_code"
              >{{item.lianlu_code}}</a-select-option>
            </a-select>
          </template>
          <template v-if="column.dataIndex === 'error_info'">
            <a-input v-model:value="record.error_info" />
          </template>
          <template v-if="column.dataIndex === 'notice'">
            <a-input v-model:value="record.notice" />
          </template>
          <template v-if="column.dataIndex === 'delay_time'">
            <a-input v-model:value="record.delay_time" />
          </template>
          <template v-if="column.dataIndex === 'feed_back_user'">
            <a-input v-model:value="record.feed_back_user" />
          </template>
          <template v-if="column.dataIndex === 'feed_back'">
            <a-input v-model:value="record.feed_back" />
          </template>
          <template v-if="column.dataIndex === 'operation'">
            <a-popconfirm
              title="确定要删除这一条链路吗?"
              ok-text="是"
              cancel-text="否"
              @confirm="delZongju(record.lianlu_code)"
            >
              <a href="#" style="color: red">删除</a>
            </a-popconfirm>
          </template>
        </template>
        <template #title>总局</template>
        <template #footer>
          <a-button type="primary" @click="addZongju">新增</a-button>
        </template>
      </a-table>
      <div class="br"></div>
      <a-table
        :columns="columns"
        :data-source="lianluData.neimengList"
        bordered
        :autoDataLoad="false"
        size="small"
        :pagination="false"
      >
        <template #bodyCell="{ column, record  }">
          <template v-if="column.dataIndex === 'lianlu_code'">
            <a-select
              ref="select"
              v-model:value="record.lianlu_code"
              style="width: 100%"
              :showSearch="true"
              allowClear
            >
              <a-select-option value="请选择节点名称" disabled>请选择节点名称</a-select-option>
              <a-select-option
                v-for="item in neimengLianluData"
                :key="item.lianlu_code"
                :value="item.lianlu_code"
              >{{item.lianlu_code}}</a-select-option>
            </a-select>
          </template>
          <template v-if="column.dataIndex === 'error_info'">
            <a-input v-model:value="record.error_info" />
          </template>
          <template v-if="column.dataIndex === 'notice'">
            <a-input v-model:value="record.notice" />
          </template>
          <template v-if="column.dataIndex === 'delay_time'">
            <a-input v-model:value="record.delay_time" />
          </template>
          <template v-if="column.dataIndex === 'feed_back_user'">
            <a-input v-model:value="record.feed_back_user" />
          </template>
          <template v-if="column.dataIndex === 'feed_back'">
            <a-input v-model:value="record.feed_back" />
          </template>
          <template v-if="column.dataIndex === 'operation'">
            <a-popconfirm
              title="确定要删除这一条链路吗?"
              ok-text="是"
              cancel-text="否"
              @confirm="delNeimeng(record.lianlu_code)"
            >
              <a href="#" style="color: red">删除</a>
            </a-popconfirm>
          </template>
        </template>
        <template #title>内蒙</template>
        <template #footer>
          <a-button type="primary" @click="addNeimeng">新增</a-button>
        </template>
      </a-table>
      <div class="br"></div>
      <a-table
        :columns="columns"
        :data-source="lianluData.guangdongList"
        bordered
        :autoDataLoad="false"
        size="small"
        :pagination="false"
      >
        <template #bodyCell="{ column, record  }">
          <template v-if="column.dataIndex === 'lianlu_code'">
            <a-select
              ref="select"
              v-model:value="record.lianlu_code"
              style="width: 100%"
              :showSearch="true"
              allowClear
            >
              <a-select-option value="请选择节点名称" disabled>请选择节点名称</a-select-option>
              <a-select-option
                v-for="item in guangdongLianluData"
                :key="item.lianlu_code"
                :value="item.lianlu_code"
              >{{item.lianlu_code}}</a-select-option>
            </a-select>
          </template>
          <template v-if="column.dataIndex === 'error_info'">
            <a-input v-model:value="record.error_info" />
          </template>
          <template v-if="column.dataIndex === 'notice'">
            <a-input v-model:value="record.notice" />
          </template>
          <template v-if="column.dataIndex === 'delay_time'">
            <a-input v-model:value="record.delay_time" />
          </template>
          <template v-if="column.dataIndex === 'feed_back_user'">
            <a-input v-model:value="record.feed_back_user" />
          </template>
          <template v-if="column.dataIndex === 'feed_back'">
            <a-input v-model:value="record.feed_back" />
          </template>
          <template v-if="column.dataIndex === 'operation'">
            <a-popconfirm
              title="确定要删除这一条链路吗?"
              ok-text="是"
              cancel-text="否"
              @confirm="delGuangdong(record.lianlu_code)"
            >
              <a href="#" style="color: red">删除</a>
            </a-popconfirm>
          </template>
        </template>
        <template #title>广东</template>
        <template #footer>
          <a-button type="primary" @click="addGuangdong">新增</a-button>
        </template>
      </a-table>
      <div class="br"></div>
      <a-table
        :columns="columns"
        :data-source="lianluData.shanghaiList"
        bordered
        :autoDataLoad="false"
        size="small"
        :pagination="false"
      >
        <template #bodyCell="{ column, record  }">
          <template v-if="column.dataIndex === 'lianlu_code'">
            <a-select
              ref="select"
              v-model:value="record.lianlu_code"
              style="width: 100%"
              :showSearch="true"
              allowClear
            >
              <a-select-option value="请选择节点名称" disabled>请选择节点名称</a-select-option>
              <a-select-option
                v-for="item in shanghaiLianluData"
                :key="item.lianlu_code"
                :value="item.lianlu_code"
              >{{item.lianlu_code}}</a-select-option>
            </a-select>
          </template>
          <template v-if="column.dataIndex === 'error_info'">
            <a-input v-model:value="record.error_info" />
          </template>
          <template v-if="column.dataIndex === 'notice'">
            <a-input v-model:value="record.notice" />
          </template>
          <template v-if="column.dataIndex === 'delay_time'">
            <a-input v-model:value="record.delay_time" />
          </template>
          <template v-if="column.dataIndex === 'feed_back_user'">
            <a-input v-model:value="record.feed_back_user" />
          </template>
          <template v-if="column.dataIndex === 'feed_back'">
            <a-input v-model:value="record.feed_back" />
          </template>
          <template v-if="column.dataIndex === 'operation'">
            <a-popconfirm
              title="确定要删除这一条链路吗?"
              ok-text="是"
              cancel-text="否"
              @confirm="delShanghai(record.lianlu_code)"
            >
              <a href="#" style="color: red">删除</a>
            </a-popconfirm>
          </template>
        </template>
        <template #title>上海</template>
        <template #footer>
          <a-button type="primary" @click="addShanghai">新增</a-button>
        </template>
      </a-table>
    </div>
    <div style="position: relative; width: 200px">
      <a-button type="primary" style="position:absolute;right:20px;top:20px" @click="saveInfo">暂存</a-button>
      <div class="makeMessageBox">
        <p style="margin-bottom: 6px">播报生成时间</p>
        <a-time-picker v-model:value="messageTime" format="HH:mm" style="width: 100%" />
        <a-button type="primary" style="margin: 10px 0;width: 45%" @click="createErrorInfo">
          <FileDoneOutlined />生 成
        </a-button>
        <a-button style="margin: 10px 0 0 10%;width: 45%" @click="copyErrorInfo">
          <CopyOutlined />复 制
        </a-button>
        <a-textarea
          id="errorInfoTextarea"
          :rows="14"
          v-model:value="errorMessageInfo"
          placeholder="播报信息"
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import dayjs, { Dayjs } from 'dayjs';
import { getAllZongjuLianlu } from "@/utils/zongjuLianlu";
import { getAllLianluListApi as getAllNeimengLianlu } from "@/utils/neimengLianlu";
import { getAllLianluListApi as getAllGuangdongLianlu } from "@/utils/guangdongLianlu";
import { getAllLianluListApi as getAllShanghaiLianlu } from "@/utils/shanghaiLianlu";
import { getAllSaveInfoApi, updataSaveInfoApi } from '@/utils/saveInfo';
import { createErrorLianluApi } from '@/utils/errorLianlu';
import { defineComponent, onMounted, reactive, ref } from "vue"
import { message } from 'ant-design-vue';
import { CopyOutlined, FileDoneOutlined } from '@ant-design/icons-vue';
const columns = [
  {
    title: '链路编号',
    dataIndex: 'lianlu_code',
  },
  {
    title: '错误信息',
    dataIndex: 'error_info',
  },
  {
    title: '通知',
    dataIndex: 'notice',
  },
  {
    title: '延迟时间',
    dataIndex: 'delay_time',
  },
  {
    title: '反馈方',
    dataIndex: 'feed_back_user',
  },
  {
    title: '反馈',
    dataIndex: 'feed_back',
  },
  {
    title: '操作',
    dataIndex: 'operation',
  },
];
interface lianluDataDto {
  id?: number
  lianlu_code: string
  lianlu_name: string
  lianlu_start: string
  lianlu_end: string
  lianlu_status: number
}
interface NodeResultDto {
  code: number
  data: Array<lianluDataDto>
  message: string
}
interface SaveInfoResultDto {
  code: number
  data: Array<LianluListDto>
  message: string
}
interface LianluListDto {
  swjg: string
  lianlu_code: string
  error_info: string
  notice: string
  delay_time: string
  feed_back_user: string
  feed_back: string
}
interface ErrorLianluDto {
  id?: number
  lianlu_code: string
  lianlu_name: string
  lianlu_start: string
  lianlu_end: string
  error_time_start: string
  error_time_end: string
  error_reason: string
  plan_error: string
  record_date: string
}
interface GetAddNeedDataDto {
  lianlu_name: string;
  lianlu_start: string;
  lianlu_end: string;
}
export default defineComponent({
  components: { CopyOutlined, FileDoneOutlined },
  setup() {
    // 生成器时间初始化
    const date = new Date();
    let month = String(date.getMonth() + 1);
    let day = String(date.getDate()).padStart(2, '0');
    let hour = String(date.getHours()).padStart(2, '0');
    let minutes = String(date.getMinutes()).padStart(2, '0');
    // 生成器时间
    let messageTime = ref<Dayjs>(dayjs(`${hour}:${minutes}`, 'HH:mm'));
    // 生成的错误信息
    let errorMessageInfo = ref('');

    // 异常链路列表
    let zongjuLianluData: lianluDataDto[] = reactive([]);
    let neimengLianluData: lianluDataDto[] = reactive([]);
    let guangdongLianluData: lianluDataDto[] = reactive([]);
    let shanghaiLianluData: lianluDataDto[] = reactive([]);
    let lianluData = reactive({
      zongjuList: [] as LianluListDto[],
      neimengList: [] as LianluListDto[],
      guangdongList: [] as LianluListDto[],
      shanghaiList: [] as LianluListDto[]
    });
    // 复制错误信息
    const copyErrorInfo = function () {
      navigator.clipboard.writeText(errorMessageInfo.value)
      message.success('复制成功！')
    }
    // 生成错误信息
    const createErrorInfo = function () {
      const queryDate = new Date(String(messageTime.value));
      const queryHours = String(queryDate.getHours()).padStart(2, '0');
      const queryMinutes = String(queryDate.getMinutes()).padStart(2, '0');

      let createInfo = `#巡检播报：\n${month}月${day}日 ${queryHours}点${queryMinutes}分：\n数据支撑链路服务监控平台：\n`;
      // 省局
      if (lianluData.neimengList.length || lianluData.guangdongList.length || lianluData.shanghaiList.length) {
        createInfo += '1.省局端链路异常\n';
      } else {
        createInfo += '1.省局端链路正常\n';
      }
      // 内蒙
      if (lianluData.neimengList.length) {
        createInfo += ' 内蒙省局链路异常。\n';
        lianluData.neimengList.forEach((item, index) => {
          createInfo += ` ${index + 1}) ${createLianluText(item, neimengLianluData)}`;
          addToErrorLianlu(item, getAddNeedData(item, neimengLianluData));
        })
      } else {
        createInfo += ' 内蒙省局链路正常。\n';
      }
      // 广东
      if (lianluData.guangdongList.length) {
        createInfo += ' 广东省局链路异常。\n';
        lianluData.guangdongList.forEach((item, index) => {
          createInfo += ` ${index + 1}) ${createLianluText(item, guangdongLianluData)}`;
          addToErrorLianlu(item, getAddNeedData(item, guangdongLianluData));
        })
      } else {
        createInfo += ' 广东省局链路正常。\n';
      }
      // 上海
      if (lianluData.shanghaiList.length) {
        createInfo += ' 上海局端链路异常。\n';
        lianluData.shanghaiList.forEach((item, index) => {
          createInfo += ` ${index + 1}) ${createLianluText(item, shanghaiLianluData)}`;
          addToErrorLianlu(item, getAddNeedData(item, shanghaiLianluData));
        })
      } else {
        createInfo += ' 上海局端链路正常。\n';
      }

      // 总局
      if (lianluData.zongjuList.length) {
        createInfo += '2.总局端链路异常\n';
        lianluData.zongjuList.forEach((item, index) => {
          createInfo += ` ${index + 1}) ${createLianluText(item, zongjuLianluData)}`;
          addToErrorLianlu(item, getAddNeedData(item, zongjuLianluData));
        })
      } else {
        createInfo += '2.总局端链路正常\n';
      }
      errorMessageInfo.value = createInfo;
    }
    // 错误信息
    const createLianluText = function (target: LianluListDto, source: lianluDataDto[]) {
      let errorLianluIndex = 0;
      for (let i = 0; i < source.length; i++) {
        if (target.lianlu_code === source[i]['lianlu_code']) {
          errorLianluIndex = i;
          break;
        }
      }
      let errorInfo = `${source[errorLianluIndex]['lianlu_start']}至${source[errorLianluIndex]['lianlu_end']}编号${source[errorLianluIndex]['lianlu_code']}`;
      errorInfo += `${target['error_info']}。`;
      if (target['notice']) {
        errorInfo += `${target['notice']}。`;
      }
      if (target['feed_back']) {
        errorInfo += `\n${target['feed_back_user']}${target['feed_back']}。`;
      }
      if (target['delay_time']) {
        errorInfo += `${target['delay_time']}。`;
      }
      errorInfo += '\n';
      return errorInfo;
    }

    // 点击生成错误信息的时候调用新增异常链路信息接口，将生成的播报信息添加到异常链路信息列表里面
    const addToErrorLianlu = function (lianluInfo: LianluListDto, otherLianluInfo: GetAddNeedDataDto) {
      console.log(lianluData.zongjuList);
      let addData = {} as ErrorLianluDto;
      // 当前时间
      const date = new Date();
      // 记录日期
      const record_date = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
      // 记录时间
      const error_time_start = record_date + ` ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
      // 当前记录日期当天重复记录同一条链路，则更新其内容而不是新建一条记录。省局链路编号存在一样的，且无法避免，手动更改吧

      // 生成错误信息的字段赋值
      addData.lianlu_code = lianluInfo.lianlu_code;
      addData.lianlu_name = otherLianluInfo.lianlu_name;
      addData.lianlu_start = otherLianluInfo.lianlu_start;
      addData.lianlu_end = otherLianluInfo.lianlu_end;
      addData.error_time_start = error_time_start;
      addData.error_time_end = '';
      addData.error_reason = lianluInfo.feed_back;
      addData.plan_error = '异常';
      addData.record_date = record_date;
      createErrorLianluApi(addData);
    }
    // 根据链路编号返回链路名称，链路源端数据库，链路目标端数据库
    const getAddNeedData = function (target: LianluListDto, source: lianluDataDto[]): GetAddNeedDataDto {
      let errorLianluIndex = 0;
      for (let i = 0; i < source.length; i++) {
        if (target.lianlu_code === source[i]['lianlu_code']) {
          errorLianluIndex = i;
          break;
        }
      }
      return {
        lianlu_name: source[errorLianluIndex]['lianlu_name'],
        lianlu_start: source[errorLianluIndex]['lianlu_start'],
        lianlu_end: source[errorLianluIndex]['lianlu_end']
      }
    }

    // 新增总局链路信息
    const addZongju = function () {
      lianluData.zongjuList.push({
        swjg: 'zongju',
        lianlu_code: 'ZZ04,DSG',
        error_info: '延迟',
        notice: '已通知DSG',
        delay_time: '',
        feed_back_user: 'DSG反馈：',
        feed_back: ''
      })
    }
    // 删除总局链路信息
    const delZongju = function (lianlu_code: string) {
      for (let i = 0; i < lianluData.zongjuList.length; i++) {
        if (lianluData.zongjuList[i].lianlu_code === lianlu_code) {
          lianluData.zongjuList.splice(i, 1)
          break
        }
      }
    }
    // 新增内蒙链路信息
    const addNeimeng = function () {
      lianluData.neimengList.push({
        swjg: 'neimeng',
        lianlu_code: 'SS05,KAFKA',
        error_info: '延迟',
        notice: '已通知DSG',
        delay_time: '',
        feed_back_user: 'DSG反馈：',
        feed_back: ''
      })
    }
    // 删除内蒙链路信息
    const delNeimeng = function (lianlu_code: string) {
      for (let i = 0; i < lianluData.neimengList.length; i++) {
        if (lianluData.neimengList[i].lianlu_code === lianlu_code) {
          lianluData.neimengList.splice(i, 1)
          break
        }
      }
    }
    // 新增广东链路信息
    const addGuangdong = function () {
      lianluData.guangdongList.push({
        swjg: 'guangdong',
        lianlu_code: 'SS05,KAFKA',
        error_info: '延迟',
        notice: '已通知DSG',
        delay_time: '',
        feed_back_user: 'DSG反馈：',
        feed_back: ''
      })
    }
    // 删除广东链路信息
    const delGuangdong = function (lianlu_code: string) {
      for (let i = 0; i < lianluData.guangdongList.length; i++) {
        if (lianluData.guangdongList[i].lianlu_code === lianlu_code) {
          lianluData.guangdongList.splice(i, 1)
          break
        }
      }
    }
    // 新增上海链路信息
    const addShanghai = function () {
      lianluData.shanghaiList.push({
        swjg: 'shanghai',
        lianlu_code: 'SS05,KAFKA',
        error_info: '延迟',
        notice: '已通知DSG',
        delay_time: '',
        feed_back_user: 'DSG反馈：',
        feed_back: ''
      })
    }
    // 删除上海链路信息
    const delShanghai = function (lianlu_code: string) {
      for (let i = 0; i < lianluData.shanghaiList.length; i++) {
        if (lianluData.shanghaiList[i].lianlu_code === lianlu_code) {
          lianluData.shanghaiList.splice(i, 1)
          break
        }
      }
    }

    // 获取总局链路信息
    const getZongjuLianluList = function () {
      getAllZongjuLianlu().then((res) => {
        const result = res as unknown as NodeResultDto
        if (result.code === 200) {
          zongjuLianluData.length = 0;
          zongjuLianluData.push(...result.data)
        }
      })
    }
    // 获取内蒙链路信息
    const getNeimengLianluList = function () {
      getAllNeimengLianlu().then((res) => {
        const result = res as unknown as NodeResultDto
        if (result.code === 200) {
          neimengLianluData.length = 0;
          neimengLianluData.push(...result.data)
        }
      })
    }
    // 获取广东链路信息
    const getGuangdongLianluList = function () {
      getAllGuangdongLianlu().then((res) => {
        const result = res as unknown as NodeResultDto
        if (result.code === 200) {
          guangdongLianluData.length = 0;
          guangdongLianluData.push(...result.data)
        }
      })
    }
    // 获取上海链路信息
    const getShanghaiLianluList = function () {
      getAllShanghaiLianlu().then((res) => {
        const result = res as unknown as NodeResultDto
        if (result.code === 200) {
          shanghaiLianluData.length = 0;
          shanghaiLianluData.push(...result.data)
        }
      })
    }

    // 获取数据的异常信息，并展示到页面中
    const initSaveInfoList = function () {
      getAllSaveInfoApi().then(res => {
        const result = res as unknown as SaveInfoResultDto;
        if (result.code === 200) {
          result.data.forEach(item => {
            if (item.swjg === 'zongju') {
              lianluData.zongjuList.push(item);
            } else if (item.swjg === 'neimeng') {
              lianluData.neimengList.push(item);
            } else if (item.swjg === 'guangdong') {
              lianluData.guangdongList.push(item);
            } else if (item.swjg === 'shanghai') {
              lianluData.shanghaiList.push(item);
            }
          })
        } else {
          message.error(result.message);
        }
      })
    }

    // 保存本页的异常信息
    const saveInfo = function () {
      const needSaveInfoData: LianluListDto[] = [];
      needSaveInfoData.push(...lianluData.zongjuList, ...lianluData.neimengList, ...lianluData.guangdongList, ...lianluData.shanghaiList);
      updataSaveInfoApi(needSaveInfoData).then((res) => {
        const result = res as unknown as SaveInfoResultDto;
        if (result.code === 200) {
          message.success('保存成功！');
        } else {
          message.error(result.message);
        }
      })
    }

    onMounted(() => {
      getZongjuLianluList();
      getNeimengLianluList();
      getGuangdongLianluList();
      getShanghaiLianluList();
      initSaveInfoList();
    })
    return {
      columns,
      messageTime,
      errorMessageInfo,
      lianluData,
      zongjuLianluData,
      neimengLianluData,
      guangdongLianluData,
      shanghaiLianluData,
      // fun
      createErrorInfo,
      copyErrorInfo,
      addZongju,
      delZongju,
      addNeimeng,
      delNeimeng,
      addGuangdong,
      delGuangdong,
      addShanghai,
      delShanghai,
      saveInfo
    }
  }

})
</script>

<style scoped>
.messageWarp {
  display: flex;
  margin: 20px;
  padding: 20px;
  min-height: 90vh;
  box-shadow: 0 0 8px 2px #ddd;
}
.br {
  margin: 20px 0;
  height: 1px;
  border-top: 2px dotted #bbb;
  border-bottom: 2px dotted #bbb;
}
.makeMessageBox {
  width: 200px;
  position: fixed;
  padding: 10px;
  margin: 10px;
  top: 160px;
  box-shadow: 0 0 8px 2px #eef;
}
</style>